import * as Service from '../service/shopService'

export default {
    state: () => ({
        shopInfo: {
            data: {}
        },
        list: {
            loading: true,
            list: [],
            map: new Map()
        }
    }),
    mutations: {
        setShopInfo(state, payload) {
            state.shopInfo = payload
        },
        setCommodityList(state, list) {
            let newList = []
            let newMap = new Map();

            list.data.forEach((item, index) => {
                newList.push(item)
                newMap.set(item.id, index)
            })

            state.list.list = newList
            state.list.map = newMap
            state.list.loading = false
            console.log(state.list)
        },
        getFirst(state) {
            state.list.loading = true
        },
        update(state, list) {
            let newList = []
            let newMap = new Map();

            list.forEach((item, index) => {
                newList.push(item)
                newMap.set(item.id, index)
            })

            state.list.list = newList
            state.list.map = newMap
            state.list.loading = false
        }
    },
    actions: {
        async getShopInfo({ commit }, id) {
            let res = await Service.getInfo(id);
            commit('setShopInfo', res.data)
        },
        async getCommodityList({ commit }, id) {
            let res = await Service.getCommodityList(id);
            commit('setCommodityList', res.data)
        },
        async del({state}, data) {
            // 删除
            if (data) {
                let res = await Service.del(data)
                // 查询
                if (res.data.success) {
                    this.dispatch('get', state)
                }
            }
        },
        async udpate({commit}, data) {
            // 修改
            if (data) {
                await Service.update(data, commit)
            }
        },
        async add({commit}, data) {
            // 修改
            if (data) {
                await Service.add(data, commit)
            }
        },
    }
}